import md5 from 'js-md5';
import Cookie from 'js-cookie';
import { isDev } from '../system';
export enum HttpConfig {
    SECURITYKEY = '*&^%$!@#^&!*',
    API = 'p_1603348974',
}
export default class HttpUtil {
    public baseURL: string = import.meta.env.VITE_BASE_API;
    public static security_key: string = HttpConfig.SECURITYKEY;
    public static default_sign: any = {
        sign_time: Date.parse(new Date().toDateString()) / 1000,
        api: HttpConfig.API,
        version: '999.999.999',
        sessid: '999.999.999',
    }
    constructor() {
        if (isDev()) {
            this.baseURL = window.localStorage.getItem('baseUrl') || import.meta.env.VITE_BASE_API
        }
    }

    public static setBaseUrl(baseURL: string) {
        (this as any).baseURL = baseURL;
    }

    public setSessid(sessid: string) {
        Cookie.set(sessid, sessid)
        HttpUtil.default_sign.sessid = sessid;
    }
    // 设置签名
    public static setDefaultSign(config: any) {
        const formData = new FormData();
    }
    // 签名相关
    public static create_sign(data: any) {
        // 1、排序
        data = HttpUtil.objKeySort(data);
        // 2.拼接
        let txt = '';
        let newkey = Object.keys(data);
        for (let i = 0; i < newkey.length; i++) {
            // 如果当前参数为对象类型, 则不参与签名
            if (typeof (data[newkey[i]]) == 'object') {
                console.log(data[newkey[i]]);
                continue
            }
            // 遍历newkey数组
            txt = txt + newkey[i];
            txt = txt + '=';
            txt = txt + data[newkey[i]];
            if (i < newkey.length - 1) {
                txt = txt + '&';
            }
        }
        return md5(txt);
    }

    public static objKeySort(obj: any) {
        // 排序的函数
        let newkey = Object.keys(obj).sort(HttpUtil.sortCharter);
        let newObj: any;
        for (let i = 0; i < newkey.length; i++) {
            newObj[newkey[i]] = obj[newkey[i]];
        }
        return newObj; // 返回排好序的新对象
    }

    // 字母排序：不区分大小写
    public static sortCharter(a: string | number, b: string | number) {
        if (a.toString() > b.toString()) {
            return 1;
        } else if (a.toString() == b.toString()) {
            return 0;
        } else {
            return -1;
        }
    }
}